import React, {Component} from 'react';
import {
  View,
  Text,
  SafeAreaView,
  TouchableHighlight,
  Alert,
  StyleSheet,
  Dimensions,
} from 'react-native';
import DatePicker from 'react-native-datepicker';
import moment from 'moment';
import {ActivityIndicator} from '@ant-design/react-native';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import {ScrollView} from 'react-native-gesture-handler';
import {cwGet} from '../utils/http';
import {Table, Row} from 'react-native-table-component';
import Page from '../components/page';
export default class ErrorPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      nowDevice: global.nowDevice,
      deviceList: global.deviceList,
      tabList: [
        {label: '实时报警', tag: 'now'},
        {label: '历史报警', tag: 'all'},
      ],
      tableHead: ['消息', '时间', 'SignNo', 'SignName', 'SignValue', '车间'],
      widthArr: [500, 100, 100, 100, 100, 300],
      tableData: [],
      animating: false,
      page: null,
      isOnMessage: true, // 是否收到消息
      timeArea: [
        {label: '最近24小时', key: 'day1'},
        {label: '最近3天', key: 'day3'},
        {label: '最近一周', key: 'day7'},
        {label: '最近一月', key: 'mouth1'},
      ],
      startTime: moment()
        .subtract(2, 'hours')
        .format('YYYY-MM-DD HH:mm:ss'),
      endTime: moment().format('YYYY-MM-DD HH:mm:ss'),
      pageIndex: 1,
      totalPage: 0,
      totalCount: 0,
      ws: null,
      data: {
        message: ' ',
        warningTime: ' ',
        signNo: ' ',
        signName: ' ',
        signValue: ' ',
        isShared: false,
        deviceName: ' ',
        id: ' ',
        createTime: '',
      },
      currentTab: 'now',
    };
    const d1 = this.props.navigation.addListener('didFocus', async () => {
      this.setState({
        nowDevice: global.nowDevice,
      });
      let result;
      try {
        if (this.state.ws && this.state.ws.readyState == 1) {
        } else {
          result = await new Promise((res, rej) => {
            this.setState(
              {
                ws: new WebSocket('ws://121.36.28.99:8018/ws'),
              },
              () => {
                this.state.ws.onopen = () => {
                  this.setState({
                    ws: this.state.ws,
                  });
                  res('open');
                };
                this.state.ws.onmessage = e => {
                  console.log(e)
                  this.setState({
                    data: JSON.parse(e.data),
                  });
                };
                this.state.ws.onerror = e => {
                  this.setState({
                    ws: this.state.ws,
                  });
                  rej('error');
                };
                this.state.ws.onclose = e => {
                  this.setState({
                    ws: this.state.ws,
                  });
                  console.log('close');
                };
              },
            );
          });
        }
      } catch (e) {
        Alert.alert("Socket 连接错误")
      }
    });
  }
  async onTabClick(e) {
    this.setState({
      currentTab: e,
    });
  }

  onTimeChange(key) {
    let startTime = '';
    let endTime = '';
    let hasPage = '';
    const now = moment();
    endTime = now.format('YYYY-MM-DD HH:mm:ss');
    switch (key) {
      case 'hour1':
        startTime = now.subtract(1, 'hours').format('YYYY-MM-DD HH:mm:ss');
        hasPage = 'h-1';
        break;
      case 'hour2':
        startTime = now.subtract(2, 'hours').format('YYYY-MM-DD HH:mm:ss');
        hasPage = 'h-2';
        break;
      case 'hour4':
        startTime = now.subtract(4, 'hours').format('YYYY-MM-DD HH:mm:ss');
        hasPage = 'h-4';
        break;
      case 'hour6':
        startTime = now.subtract(6, 'hours').format('YYYY-MM-DD HH:mm:ss');
        hasPage = 'h-6';
        break;
      case 'hour8':
        startTime = now.subtract(8, 'hours').format('YYYY-MM-DD HH:mm:ss');
        hasPage = 'h-8';
        break;
      case 'hour12':
        startTime = now.subtract(12, 'hours').format('YYYY-MM-DD HH:mm:ss');
        hasPage = 'h-12';
        break;
      case 'hour16':
        startTime = now.subtract(16, 'hours').format('YYYY-MM-DD HH:mm:ss');
        hasPage = 'h-16';
        break;
      case 'day1':
        startTime = now.subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss');
        hasPage = 'd-1';
        break;
      case 'day3':
        startTime = now.subtract(3, 'days').format('YYYY-MM-DD HH:mm:ss');
        break;
      case 'day7':
        startTime = now.subtract(7, 'days').format('YYYY-MM-DD HH:mm:ss');
        break;
      case 'mouth1':
        startTime = now.subtract(1, 'months').format('YYYY-MM-DD HH:mm:ss');
        break;
    }
    this.setState(
      {
        startTime: startTime,
        endTime: endTime,
        hasPage,
      },
      () => {
        this.getErrorData();
      },
    );
  }
  onRef = ref => {
    this.state.page = ref;
  };

  callBack(e) {
    this.setState(
      {
        pageIndex: e,
      },
      () => {
        this.getErrorData();
      },
    );
  }

  async getErrorData() {
    console.log(this.state.startTime, this.state.endTime);
    this.setState({
      animating: true,
      tableData: [],
    });
    try {
      let res = await cwGet(
        'WarningData/GetWarnedData?start=' +
          encodeURIComponent(this.state.startTime) +
          '&end=' +
          encodeURIComponent(this.state.endTime) +
          '&pageIndex=' +
          this.state.pageIndex,
      );
      this.setState({
        totalCount: res.totlalCount,
        totalPage: Math.ceil(res.totlalCount / 20.0),
      });
      console.log(res);
      if (res && res.list.length != 0) {
        let res_s = [];
        res.list.forEach((rowData, index) => {
          res_s.push(
            <Row
              key={index}
              data={[
                rowData.message,
                rowData.warningTime,
                rowData.signNo,
                rowData.signName,
                rowData.signValue,
                rowData.isShared ? '6、7车间' : rowData.deviceName,
              ]}
              widthArr={this.state.widthArr}
              style={[
                NowDataStyles.row,
                index % 2 == 0 && {backgroundColor: '#DDCCF7'},
              ]}
            />,
          );
        });
        this.setState(
          {
            tableData: res_s,
          },
          () => {
            this.setState({
              animating: false,
            });
          },
        );
      } else {
        Alert.alert('提示', '数据为空');
        this.setState({
          animating: false,
        });
      }
    } catch (e) {
      console.log(e);
      Alert.alert('提示', '网络错误');
      this.setState({
        animating: false,
      });
    }
  }

  render() {
    return (
      <SafeAreaView style={{flex: 1, backgroundColor: '#fff'}}>
        <View
          style={{
            width: '100%',
            height: 55,
            justifyContent: 'center',
            backgroundColor: '#fff',
            shadowColor: '#1a5050BB',
            shadowOffset: {width: 0, height: 1},
            shadowOpacity: 1,
            shadowRadius: 2, //模糊半径
            elevation: 4, //这个决定阴影的大小
          }}>
          <Text style={{fontSize: 20, marginLeft: 25}}>报警信息</Text>
        </View>
        <View
          style={{
            marginLeft: 20,
            flexDirection: 'row',
            marginTop: 5,
            alignItems: 'center',
          }}>
          <FontAwesome
            style={{backgroundColor: 'transparent', marginRight: 20}}
            name="bars"
            color="grey"
            size={16}
          />
          <Text style={{fontSize: 16}}>报警信息</Text>
          {this.state.nowDevice.name.length > 0 ? (
            <FontAwesome
              style={{
                backgroundColor: 'transparent',
                marginRight: 10,
                marginLeft: 10,
              }}
              name="chevron-left"
              color="grey"
              size={16}
            />
          ) : (
            <View></View>
          )}
          <Text>{this.state.nowDevice.name}</Text>
        </View>

        <View style={{flexDirection: 'row', width: '100%'}}>
          {this.state.tabList.map(item => {
            return (
              <TouchableHighlight
                underlayColor={'#fff'}
                key={item.id}
                style={{
                  flex: 1,
                  flexDirection: 'row',
                  justifyContent: 'center',
                  paddingTop: 4,
                  paddingBottom: 4,
                  marginTop: 5,
                }}
                onPress={this.onTabClick.bind(this, item.tag)}>
                <View
                  style={[
                    {width: '85%', backgroundColor: '#D5D6D8'},
                    this.state.currentTab === item.tag
                      ? NowDataStyles.curretnTab
                      : '',
                  ]}>
                  <Text
                    style={{fontSize: 16, textAlign: 'center', color: '#fff'}}>
                    {item.label}
                  </Text>
                </View>
              </TouchableHighlight>
            );
          })}
        </View>
        <ScrollView style={{height: '100%'}}>
          <View
            style={{
              display: this.state.currentTab === 'now' ? 'flex' : 'none',
            }}>
            <Text style={{marginLeft: 20}}>
              {this.state.ws && this.state.ws.readyState == 1
                ? 'socket已连接'
                : 'socket未连接'}
            </Text>
            {this.state.isOnMessage ? (
              <View style={{margin: 10, marginTop: 20}}>
                <View style={NowDataStyles.container}>
                  <Text style={NowDataStyles.text}>消息</Text>
                  <Text>{this.state.data.message}</Text>
                </View>
                <View style={NowDataStyles.container}>
                  <Text style={NowDataStyles.text}>signName</Text>
                  <Text>{this.state.data.signName}</Text>
                </View>
                <View style={NowDataStyles.container}>
                  <Text style={NowDataStyles.text}>signNo</Text>
                  <Text>{this.state.data.signNo}</Text>
                </View>
                <View style={NowDataStyles.container}>
                  <Text style={NowDataStyles.text}>signValue</Text>
                  <Text>{this.state.data.signValue}</Text>
                </View>
                <View style={NowDataStyles.container}>
                  <Text style={NowDataStyles.text}>报警时间</Text>
                  <Text>{this.state.data.warningTime}</Text>
                </View>
                <View style={NowDataStyles.container}>
                  <Text style={NowDataStyles.text}>车间</Text>
                  <Text>
                    {this.state.data.isShared
                      ? '6、7车间'
                      : this.state.data.deviceName}
                  </Text>
                </View>
              </View>
            ) : (
              <View style={{justifyContent: 'center'}}>
                <Text style={{textAlign: 'center'}}>未接收到报警</Text>
              </View>
            )}
          </View>
          <View
            style={{
              display: this.state.currentTab === 'all' ? 'flex' : 'none',
            }}>
            <View style={{flexDirection: 'row', flexWrap: 'wrap'}}>
              {this.state.timeArea.map(item => {
                return (
                  <TouchableHighlight
                    underlayColor="#dcdcdc"
                    onPress={this.onTimeChange.bind(this, item.key, true)}>
                    <Text
                      style={{
                        marginLeft: 10,
                        fontSize: 12,
                        marginRight: 5,
                        padding: 4,
                      }}>
                      {item.label}
                    </Text>
                  </TouchableHighlight>
                );
              })}
            </View>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                paddingLeft: 16,
                paddingRight: 10,
                justifyContent: 'space-between',
              }}>
              <View style={{flexDirection: 'row', alignItems: 'center'}}>
                <Text>时间：</Text>
                <DatePicker
                  style={{
                    width: Dimensions.get('window').width / 3,
                    fontSize: 12,
                  }}
                  date={this.state.startTime}
                  mode="datetime"
                  placeholder="选择日期"
                  format="YYYY-MM-DD HH:mm"
                  showIcon={false}
                  is24Hour={true}
                  confirmBtnText="确定"
                  cancelBtnText="取消"
                  customStyles={{
                    dateInput: {
                      height: 30,
                      borderColor: '#E2B0B0',
                      borderRadius: 3,
                      overflow: 'hidden',
                    },
                  }}
                  onDateChange={date => {
                    this.setState({startTime: date});
                  }}
                />
                <View style={{flexDirection: 'row', height: 30}}>
                  <Text style={{marginLeft: 3, marginRight: 3, marginTop: 5}}>
                    -
                  </Text>
                </View>
                <DatePicker
                  style={{
                    width: Dimensions.get('window').width / 3,
                    fontSize: 12,
                  }}
                  date={this.state.endTime}
                  mode="datetime"
                  placeholder="选择日期"
                  format="YYYY-MM-DD HH:mm"
                  showIcon={false}
                  is24Hour={true}
                  confirmBtnText="确定"
                  cancelBtnText="取消"
                  customStyles={{
                    dateInput: {
                      height: 30,
                      borderColor: '#E2B0B0',
                      borderRadius: 3,
                      overflow: 'hidden',
                    },
                  }}
                  onDateChange={date => {
                    this.setState({endTime: date});
                  }}
                />
              </View>
              <TouchableHighlight
                underlayColor="#dcdcdc"
                style={{
                  height: 30,
                  flexDirection: 'row',
                  padding: 5,
                  borderRadius: 3,
                  alignItems: 'center',
                  backgroundColor: '#E8B5E1',
                }}
                onPress={this.getErrorData.bind(this)}>
                <Text>查询</Text>
              </TouchableHighlight>
            </View>
            <ScrollView
              horizontal={true}
              style={{
                height: Dimensions.get('window').height - 330,
                marginHorizontal: 5,
              }}>
              {this.state.tableData.length > 0 ? (
                <View>
                  <Table borderStyle={{borderWidth: 1, borderColor: '#808080'}}>
                    <Row
                      data={this.state.tableHead}
                      widthArr={this.state.widthArr}
                      style={NowDataStyles.header}
                      textStyle={NowDataStyles.text}
                    />
                  </Table>
                  <ScrollView
                    horizontal={false}
                    style={(NowDataStyles.dataWrapper, {})}>
                    <Table
                      borderStyle={{borderWidth: 0.5, borderColor: '#808080'}}>
                      {this.state.tableData}
                    </Table>
                  </ScrollView>
                </View>
              ) : (
                <></>
              )}
            </ScrollView>
          </View>
        </ScrollView>
        
        <ActivityIndicator
              animating={this.state.animating}
              toast
              size="large"
              text="加载中..."
            />
        {this.state.totalPage != 0 ? (
          <View>
            <View style={{paddingLeft: 10, paddingRight: 10}}>
              <Text>共{this.state.totalCount}条</Text>
            </View>
            <Page
              PageAllNum={this.state.totalPage}
              onRef={this.onRef}
              activePage={1}
              callBack={CB => this.callBack(CB)}
            />
          </View>
        ) : (
          <View></View>
        )}
      </SafeAreaView>
    );
  }
}
const NowDataStyles = StyleSheet.create({
  nextTab: {
    borderWidth: 1,
    borderColor: '#E8C1C1',
    backgroundColor: '#F4F4F4',
    color: '#B2B2B2',
  },
  curretnTab: {
    backgroundColor: '#638AD0',
  },
  container: {
    borderBottomWidth: 0.4,
    paddingHorizontal: 10,
    paddingVertical: 15,
    marginBottom: 5,
  },
  header: {
    height: 30,
    borderBottomWidth: 0,
    borderTopWidth: 1,
    backgroundColor: '#BBCCF7',
    borderBottomWidth: 1,
  },
  text: {fontSize: 16, fontWeight: '700'},
  dataWrapper: {marginTop: -1},
  row: {height: 40, backgroundColor: '#DDEBF7'},
  wrapper: {flexDirection: 'row'},
});
